/*
 * All rights reserved.  http://www.tansun.com.cn
 *
 * This software is the confidential and proprietary information of Tansun Tech Corporation ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Tansun Tech.
 */
/**
 *
 */
package com.tansun.tandata.utils;


import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.Map;

/**
 * <pre>
 *
 * </pre>
 *
 * @author linqingyang<br>
 * <b>mail</b> linqingyang@tansun.com.cn<br>
 * <b>date</b> 2020-06-03 10:26<br>
 * @version 1.0.1
 * @Record <pre>
 * 版本               修改人              修改日期 		 修改内容描述
 * ----------------------------------------------
 * 1.0.1 	linqingyang 	2020-06-03      创建
 * ----------------------------------------------
 * </pre>
 */
@Slf4j
public class FreemarkUtil {

    private static final String TEMPLATE_DIR_NAME = "codeTemplate";

    private static final String GENERATE_ERROR_MSG = "Error generating code!";

    public static void generateCode(Map<String, Object> params, String ftlPath, String saveFilePath) throws IOException {
        String code = generateCode(params, ftlPath);

        IOUtils.write(code, new FileOutputStream(new File(saveFilePath)));
    }

    public static String generateCode(Map<String, Object> params, String ftlPath){
        String code = null;
        try {
            Configuration configuration = new Configuration(Configuration.getVersion());
            File file = ResourceUtils.getFile(getTemplateDirPath(ftlPath));
            configuration.setDirectoryForTemplateLoading(file);
            configuration.setDefaultEncoding("utf-8");
            Template template = configuration.getTemplate(ftlPath);
            Writer out = new StringWriter(2048);
            template.process(params, out);
            code = out.toString();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            code = GENERATE_ERROR_MSG;
            log.error("根据模板生成代码出错", e);
        }
        return code;
    }

    private static String getTemplateDirPath(String ftlPath){
        return ResourceUtils.CLASSPATH_URL_PREFIX + TEMPLATE_DIR_NAME;
    }
}
